// ------------------ 全局变量 ------------------
const STORAGE_PREFIX = "东方仙盟开源酒店系统_";
let mer_id = "默认商户ID"; // 可根据需求动态设置
let store_id = "默认门店ID"; // 可根据需求动态设置

// 页面初始化：加载基础数据、默认显示收银台
/*
window.onload = function() {
  loadRoomTypes();
  loadFloors();
  loadRooms();
  loadDepositOrders();
  showPage("reception");
  renderRoomStatus();
};
*/
// ------------------ 左侧 Nav 切换页面 ------------------
function 东方仙盟菜单_显示_主页面(pageId) {
  const pages = document.getElementsByClassName("page");
  for (let i = 0; i < pages.length; i++) {
    pages[i].style.display = "none";
  }
  document.getElementById(pageId + "Page").style.display = "block";
}

 // 切换页面
    function 东方仙盟菜单_显示_子页面(pageId) {
      const pages = document.querySelectorAll('.东方仙盟子页面');
      pages.forEach(page => {
        page.style.display = 'none';
      });
      
      document.getElementById(pageId + 'Page').style.display = 'block';
    }

function 东方仙盟菜单_关闭模态(灵体) {
  document.getElementById(灵体).style.display = "none";
}

// 收缩/展开左侧 Nav
function toggleSidebar() {
  const sidebar = document.getElementById("sidebar");
  sidebar.classList.toggle("collapsed");
}

// ------------------ 基础资料：房型管理（localStorage） ------------------
// 保存房型
function saveRoomType() {
  const id = document.getElementById("roomTypeId").value;
  const name = document.getElementById("roomTypeName").value;
  const price = document.getElementById("roomTypePrice").value;
  const deposit = document.getElementById("roomTypeDeposit").value;
  
  if (!id || !name || !price || !deposit) {
    alert("请填写完整信息");
    return;
  }

  const roomTypes = getLocalStorage("roomTypes") || [];
  // 判断是否已存在，存在则修改，否则新增
  const index = roomTypes.findIndex(item => item.id === id);
  if (index > -1) {
    roomTypes[index] = { id, name, price, deposit };
  } else {
    roomTypes.push({ id, name, price, deposit });
  }
  setLocalStorage("roomTypes", roomTypes);
  loadRoomTypes(); // 重新渲染列表
  clearRoomTypeInputs();
}

// 删除房型
function deleteRoomType() {
  const id = document.getElementById("roomTypeId").value;
  const roomTypes = getLocalStorage("roomTypes") || [];
  const newRoomTypes = roomTypes.filter(item => item.id !== id);
  setLocalStorage("roomTypes", newRoomTypes);
  loadRoomTypes();
  clearRoomTypeInputs();
}
/*
// 加载房型列表
function loadRoomTypes() {
  const roomTypes = getLocalStorage("roomTypes") || [];
  const listDom = document.getElementById("roomTypeList");
  listDom.innerHTML = "";
  roomTypes.forEach(item => {
    const li = document.createElement("li");
    li.innerText = `ID: ${item.id} | 名称: ${item.name} | 房价: ${item.price} | 押金: ${item.deposit}`;
    listDom.appendChild(li);
  });
}
*/

// 清空房型输入框
function clearRoomTypeInputs() {
  document.getElementById("roomTypeId").value = "";
  document.getElementById("roomTypeName").value = "";
  document.getElementById("roomTypePrice").value = "";
  document.getElementById("roomTypeDeposit").value = "";
}

// ------------------ 基础资料：楼层管理（localStorage） ------------------
// 保存楼层
function saveFloor() {
  const id = document.getElementById("floorId").value;
  const name = document.getElementById("floorName").value;
  const sort = document.getElementById("floorSort").value;
  
  if (!id || !name || !sort) {
    alert("请填写完整信息");
    return;
  }

  const floors = getLocalStorage("floors") || [];
  const index = floors.findIndex(item => item.id === id);
  if (index > -1) {
    floors[index] = { id, name, sort };
  } else {
    floors.push({ id, name, sort });
  }
  setLocalStorage("floors", floors);
  loadFloors();
  clearFloorInputs();
}

// 删除楼层
function deleteFloor() {
  const id = document.getElementById("floorId").value;
  const floors = getLocalStorage("floors") || [];
  const newFloors = floors.filter(item => item.id !== id);
  setLocalStorage("floors", newFloors);
  loadFloors();
  clearFloorInputs();
}
/*
// 加载楼层列表
function loadFloors() {
  const floors = getLocalStorage("floors") || [];
  const listDom = document.getElementById("floorList");
  listDom.innerHTML = "";
  floors.forEach(item => {
    const li = document.createElement("li");
    li.innerText = `ID: ${item.id} | 名称: ${item.name} | 序号: ${item.sort}`;
    listDom.appendChild(li);
  });
}
*/
// 清空楼层输入框
function clearFloorInputs() {
  document.getElementById("floorId").value = "";
  document.getElementById("floorName").value = "";
  document.getElementById("floorSort").value = "";
}

// ------------------ 基础资料：房间管理（localStorage） ------------------
// 保存房间
function saveRoom() {
  const id = document.getElementById("roomId").value;
  const roomTypeId = document.getElementById("roomTypeIdSelect").value;
  const floorId = document.getElementById("roomFloorIdSelect").value;
  const name = document.getElementById("roomName").value;
  const sort = document.getElementById("roomSort").value;
  
  if (!id || !roomTypeId || !floorId || !name || !sort) {
    alert("请填写完整信息");
    return;
  }

  const rooms = getLocalStorage("rooms") || [];
  const index = rooms.findIndex(item => item.id === id);
  if (index > -1) {
    rooms[index] = { id, roomTypeId, floorId, name, sort };
  } else {
    rooms.push({ id, roomTypeId, floorId, name, sort });
  }
  setLocalStorage("rooms", rooms);
  loadRooms();
  clearRoomInputs();
  renderRoomStatus(); // 房间变动后重新渲染房态
}

// 删除房间
function deleteRoom() {
  const id = document.getElementById("roomId").value;
  const rooms = getLocalStorage("rooms") || [];
  const newRooms = rooms.filter(item => item.id !== id);
  setLocalStorage("rooms", newRooms);
  loadRooms();
  clearRoomInputs();
  renderRoomStatus(); // 房间变动后重新渲染房态
}

// 加载房间列表
function loadRooms() {
  const rooms = getLocalStorage("rooms") || [];
  const listDom = document.getElementById("roomList");
  listDom.innerHTML = "";
  rooms.forEach(item => {
    const li = document.createElement("li");
    li.innerText = `ID: ${item.id} | 房型ID: ${item.roomTypeId} | 楼层ID: ${item.floorId} | 名称: ${item.name} | 序号: ${item.sort}`;
    listDom.appendChild(li);
  });
}

// 清空房间输入框
function clearRoomInputs() {
  document.getElementById("roomId").value = "";
  document.getElementById("roomTypeIdSelect").value = "";
  document.getElementById("roomFloorIdSelect").value = "";
  document.getElementById("roomName").value = "";
  document.getElementById("roomSort").value = "";
}


// 之前的代码保持不变...

// 修改渲染房态函数，使用卡片式布局
function renderRoomStatus() {
  const rooms = getLocalStorage("rooms") || [];
  const roomTypes = getLocalStorage("roomTypes") || [];
  const container = document.getElementById("roomStatusContainer");
  container.innerHTML = "";

  rooms.forEach(room => {
    // 根据 roomTypeId 匹配房型信息
    const roomType = roomTypes.find(type => type.id === room.roomTypeId) || { name: "未知房型", price: "未知", deposit: "未知" };
    
    // 检查房间是否已被占用
    const isOccupied = checkRoomOccupied(room.id);
    
    const card = document.createElement("div");
    card.className = `room-card ${isOccupied ? 'occupied' : 'available'}`;
    card.onclick = () => openCreateOrderModal(room.id, room.name, roomType.deposit);
    
    card.innerHTML = `
      <div class="room-number">${room.name}</div>
      <div class="room-type">${roomType.name}</div>
      <div class="room-status">${isOccupied ? '已入住' : '空闲'}</div>
    `;
    
    container.appendChild(card);
  });
}

// 之前的其他代码保持不变...
// 之前的代码保持不变...

// 渲染房态表格，为房号添加点击事件
function renderRoomStatus作废2() {
  const rooms = getLocalStorage("rooms") || [];
  const roomTypes = getLocalStorage("roomTypes") || [];
  const tableBody = document.getElementById("roomStatusTableBody");
  tableBody.innerHTML = "";

  rooms.forEach(room => {
    // 根据 roomTypeId 匹配房型信息
    const roomType = roomTypes.find(type => type.id === room.roomTypeId) || { name: "未知房型", price: "未知", deposit: "未知" };
    
    // 检查房间是否已被占用
    const isOccupied = checkRoomOccupied(room.id);
    
    const tr = document.createElement("tr");
    tr.innerHTML = `
      <td>
        <span class="room-number ${isOccupied ? 'occupied' : 'available'}" 
              onclick="openCreateOrderModal('${room.id}', '${room.name}', '${roomType.deposit}')">
          ${room.name}
        </span>
      </td>
      <td>${roomType.name}</td>
      <td>${isOccupied ? '已入住' : '空闲'}</td>
    `;
    tableBody.appendChild(tr);
  });
}

// 检查房间是否已被占用
function checkRoomOccupied(roomId) {
  const orders = getLocalStorage("depositOrders") || [];
  return orders.some(order => order.room_id === roomId && order.status === 2); // 2表示在住
}

// 打开创建订单模态框
function openCreateOrderModal(roomId, roomName, depositPrice) {
  document.getElementById("modalRoomId").value = roomId;
  document.getElementById("modalRoomName").textContent = roomName;
  document.getElementById("modalDepositPrice").textContent = depositPrice;
  document.getElementById("modalUserId").value = "";
  document.getElementById("modalUserName").value = "";
  document.getElementById("modalUserPhone").value = "";
  
  // 显示模态框
  document.getElementById("createOrderModal").style.display = "block";
}

// 关闭模态框
function closeModal() {
  document.getElementById("createOrderModal").style.display = "none";
}

// 提交创建订单
function submitCreateOrder() {
  const roomId = document.getElementById("modalRoomId").value;
  const userId = document.getElementById("modalUserId").value;
  const userName = document.getElementById("modalUserName").value;
  const userPhone = document.getElementById("modalUserPhone").value;
  const depositPrice = document.getElementById("modalDepositPrice").textContent;
  
  if (!roomId || !userId || !userName || !userPhone) {
    alert("请填写完整信息");
    return;
  }
  
  // 获取房间信息
  const rooms = getLocalStorage("rooms") || [];
  const room = rooms.find(r => r.id === roomId);
  
  if (!room) {
    alert("房间不存在");
    return;
  }
  
  // 获取房型信息以确定房价
  const roomTypes = getLocalStorage("roomTypes") || [];
  const roomType = roomTypes.find(t => t.id === room.roomTypeId);
  
  if (!roomType) {
    alert("房型信息不存在");
    return;
  }
  
  // 创建订单对象
  const newOrder = {
    cyber_id: getNextCyberId(),
    cyber_sn: generateCyberSn(),
    mer_id: mer_id,
    store_id: store_id,
    name: userName,
    room_id: roomId,
    room_name: room.name,
    total_price: parseFloat(roomType.price),
    price: parseFloat(roomType.price),
    deposit_price: parseFloat(depositPrice),
    userid: userId,
    username: userName,
    userphone: userPhone,
    create_time: Date.now(),
    pay_time: null,
    discount_price: 0,
    status: 2, // 2: 在住
    pay_type: "现金",
    auth_code: "",
    checkout_time: null,
    remarks: ""
  };
  
  // 保存订单到 localStorage
  const orders = getLocalStorage("depositOrders") || [];
  orders.push(newOrder);
  setLocalStorage("depositOrders", orders);
  
  // 关闭模态框
  closeModal();
  
  // 刷新订单列表和房态
  loadDepositOrders();
  renderRoomStatus();
  
  alert("订单创建成功！");
}

// 新增一些CSS样式
const style = document.createElement('style');
style.textContent = `
  .modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    width: 400px;
    max-width: 90%;
  }
  
  .modal-content div {
    margin-bottom: 10px;
  }
  
  .room-number {
    cursor: pointer;
    text-decoration: underline;
  }
  
  .room-number.available {
    color: green;
  }
  
  .room-number.occupied {
    color: red;
  }
`;
document.head.appendChild(style);

// ------------------ 收银台：房态渲染 ------------------
function renderRoomStatus作废() {
  const rooms = getLocalStorage("rooms") || [];
  const roomTypes = getLocalStorage("roomTypes") || [];
  const tableBody = document.getElementById("roomStatusTableBody");
  tableBody.innerHTML = "";

  rooms.forEach(room => {
    // 根据 roomTypeId 匹配房型信息
    const roomType = roomTypes.find(type => type.id === room.roomTypeId) || { name: "未知房型", price: "未知", deposit: "未知" };
    
    const tr = document.createElement("tr");
    tr.innerHTML = `
      <td>${room.name}</td>
      <td>${roomType.name}</td>
      <td>空房</td> <!-- 可扩展：结合订单状态判断实际房态 -->
    `;
    tableBody.appendChild(tr);
  });
}

// ------------------ 押金管理：订单操作（localStorage） ------------------
// 生成唯一 cyber_id（自动递增）
function getNextCyberIdAI断层() {
  const orders = getLocalStorage("depositOrders") || [];
  const maxId = orders.reduce((max, item) => (item.cyber_id > max ? item.cyber_id : max), 0);
  return maxId + 1;
}


// 生成唯一 cyber_id（自动递增）
function getNextCyberId() {
  const orders = getLocalStorage("depositOrders") || [];
  const maxId = orders.reduce((max, item) => (item.cyber_id > max ? item.cyber_id : max), 0);
  return maxId + 1;
}

// 生成32位随机字符作为 cyber_sn
function generateCyberSn() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < 32; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 创建新订单（开房 + 押金）
function createDepositOrder() {
  // 模拟表单输入，实际应通过表单获取
  const roomId = prompt("请输入房间ID");
  const userId = prompt("请输入客人身份证号");
  const userName = prompt("请输入客人姓名");
  const userPhone = prompt("请输入客人手机号");
  
  if (!roomId || !userId || !userName || !userPhone) {
    alert("请填写完整信息");
    return;
  }
  
  // 获取房间信息
  const rooms = getLocalStorage("rooms") || [];
  const room = rooms.find(r => r.id === roomId);
  
  if (!room) {
    alert("房间不存在");
    return;
  }
  
  // 获取房型信息以确定押金金额
  const roomTypes = getLocalStorage("roomTypes") || [];
  const roomType = roomTypes.find(t => t.id === room.roomTypeId);
  
  if (!roomType) {
    alert("房型信息不存在");
    return;
  }
  
  // 创建订单对象
  const newOrder = {
    cyber_id: getNextCyberId(),
    cyber_sn: generateCyberSn(),
    mer_id: mer_id,
    store_id: store_id,
    name: userName,
    room_name: room.name,
    total_price: parseFloat(roomType.price),
    price: parseFloat(roomType.price),
    deposit_price: parseFloat(roomType.deposit),
    userid: userId,
    username: userName,
    userphone: userPhone,
    create_time: Date.now(),
    pay_time: null,
    discount_price: 0,
    status: 2, // 2: 在住
    pay_type: "现金",
    auth_code: "",
    checkout_time: null,
    remarks: ""
  };
  
  // 保存订单到 localStorage
  const orders = getLocalStorage("depositOrders") || [];
  orders.push(newOrder);
  setLocalStorage("depositOrders", orders);
  
  // 刷新订单列表和房态
  loadDepositOrders();
  renderRoomStatus();
  
  alert("订单创建成功！");
}

// 退房并处理押金
function checkoutRoom(orderId) {
  const orders = getLocalStorage("depositOrders") || [];
  const orderIndex = orders.findIndex(o => o.cyber_id === orderId);
  
  if (orderIndex === -1) {
    alert("订单不存在");
    return;
  }
  
  const order = orders[orderIndex];
  
  // 确认退房
  if (confirm(`确认退房并处理押金？\n房间号：${order.room_name}\n客人姓名：${order.username}\n押金金额：${order.deposit_price}`)) {
    // 更新订单状态
    order.status = 1; // 1: 已退房
    order.checkout_time = Date.now();
    
    // 模拟押金退回操作
    alert(`押金 ${order.deposit_price} 元已原路退回！`);
    
    // 保存更新后的订单
    orders[orderIndex] = order;
    setLocalStorage("depositOrders", orders);
    
    // 刷新订单列表和房态
    loadDepositOrders();
    renderRoomStatus();
  }
}

// 加载押金订单列表
function loadDepositOrders() {
  const orders = getLocalStorage("depositOrders") || [];
  const tableBody = document.getElementById("depositTableBody");
  tableBody.innerHTML = "";
  
  orders.forEach(order => {
    const tr = document.createElement("tr");
    
    // 根据状态设置不同样式
    if (order.status === 2) {
      tr.style.backgroundColor = "#fff3cd"; // 黄色背景表示在住
    }
    
    tr.innerHTML = `
      <td>${order.cyber_sn}</td>
      <td>${order.room_name}</td>
      <td>${order.username}</td>
      <td>${order.total_price}</td>
      <td>${order.status === 2 ? "在住" : "已退房"}</td>
      <td>
        ${order.status === 2 ? 
          `<button onclick="checkoutRoom(${order.cyber_id})">退房</button>` : 
          '已完成'}
      </td>
    `;
    tableBody.appendChild(tr);
  });
}

// ------------------ localStorage 通用操作函数 ------------------
// 带前缀的 localStorage 获取
function getLocalStorage(key) {
  const prefixedKey = STORAGE_PREFIX + key;
  const data = localStorage.getItem(prefixedKey);
  return data ? JSON.parse(data) : null;
}

// 带前缀的 localStorage 设置
function setLocalStorage(key, value) {
  const prefixedKey = STORAGE_PREFIX + key;
  localStorage.setItem(prefixedKey, JSON.stringify(value));
}

// 清空所有酒店系统相关的 localStorage 数据
function clearAllData() {
  if (confirm("确定要清空所有酒店系统数据吗？此操作不可恢复！")) {
    const keysToRemove = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key.startsWith(STORAGE_PREFIX)) {
        keysToRemove.push(key);
      }
    }
    
    keysToRemove.forEach(key => localStorage.removeItem(key));
    alert("所有数据已清空！");
    
    // 刷新页面
    location.reload();
  }
}

// ------------------ 工具函数 ------------------
// 格式化时间戳为可读日期时间
function formatDateTime(timestamp) {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
}

// 数字补零
function padZero(num) {
  return num < 10 ? "0" + num : num;
}